<template>
  <div>
    <el-dialog
      :title="type=='edit'?'编辑':'新增'"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="closeEditDialog"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-form
        :model="addInfo"
        :rules="rules"
        ref="refAddInfo"
        label-width="110px"
      >
        <el-form-item size="small" label="产品Key" prop="productKey">
          <el-input
            clearable
            v-model.trim="addInfo.productKey"
            placeholder="请输入产品Key"
            maxlength="30"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item size="small" label="产品名称" prop="name">
          <el-input
            clearable
            v-model.trim="addInfo.name"
            placeholder="请输入产品名称"
            maxlength="30"
            :disabled="type == 'view'"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item size="small" label="产品类型" prop="category">
          <el-input
            clearable
            v-model.trim="addInfo.category"
            placeholder="请输入产品类型"
            maxlength="32"
            :disabled="type == 'view'"
            oninput="value=value.replace(/[^\w_]/g,'');"
          ></el-input>
        </el-form-item> -->

        <el-form-item size="small" label="产品图片" prop="img">
          <el-upload
            :class="{ disabled: uploadDisabled }"
            :on-remove="handleRemove"
            :on-change="uploadSectionFile"
            :action="baseUrl"
            list-type="picture-card"
            accept=".jpg,.png"
            :on-preview="handlePictureCardPreview"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
            :on-success="handleSuccessFunction"
            :limit="1"
            :on-exceed="handleExceedScene"
            :file-list="fileList"
            :on-error="uploadFileError"
            :disabled="type == 'view'"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeEditDialog" class="cancel-button">取 消</el-button>
        <el-button
          size="small"
          @click="editSubmit"
          v-preventReClick="1000" class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible2" class="el_dialog">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { provinceCityAreaArray } from "@/utils/province-city-area";
import { reqProductAdd, reqProductEdit } from "@/api/model";
import { mapState } from "vuex";
import asc from "@utils/asc.js"; //加密解密

export default {
  name: "add",
  props: ["type", "editInfo"],
  data() {
    return {
      headers: {
        token: asc.decrypt(sessionStorage.getItem("token")),
      },
      fileList: [],
      dialogImageUrl: "",
      dialogVisible2: false,
      projectList: [], //单位数据
      provinceCityAreaData: provinceCityAreaArray,
      dialogVisible: false,
      addInfo: {
        name: "",
        productKey: "",
        img: "",
      },

      // 表单验证规则
      rules: {
        productKey: [
          { required: true, message: "请输入产品Key", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        img: [
          { required: true, message: "请选择上传产品图片", trigger: "change" },
        ],
      },
      restaurants: [],
      uploadDisabled: false, //加号默认显示
    };
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        switch (this.type) {
          case "add":
            break;
          case "edit":
            this.addInfo.name = this.editInfo.name;
            this.addInfo.productKey = this.editInfo.productKey;
            this.addInfo.img = this.editInfo.img;
            if (this.editInfo.img) {
              this.fileList = [{ name: "product", url: this.editInfo.img }];
              this.uploadDisabled = true;
            }
            break;
          case "view":
            this.addInfo = this.editInfo;
            if (this.editInfo.img) {
              this.fileList = [{ name: "product", url: this.editInfo.img }];
              this.uploadDisabled = true;
            }
        }
      }
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    // 随机生成16位数key
    generateRandomString(length) {
      const characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      let result = "";
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(
          Math.floor(Math.random() * charactersLength)
        );
      }
      return result;
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [{ value: "服务" }, { value: "安防" }];
    },
    handleSelect(item) {
      // console.log(item);
    },
    uploadSectionFile(file, fileList) {
      if (fileList.length >= 1) {
        this.uploadDisabled = true; //隐藏加号
      }
    },
    //上传失败
    uploadFileError(err, file, fileList) {
      this.uploadDisabled = false;
    },
    // //删除照片
    handleRemove(file) {
      this.addInfo.img = "";
      setTimeout(() => {
        this.uploadDisabled = false;
      }, 1000);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible2 = true;
    },
    // 上传文件之前的钩子
    beforeAvatarUpload(file) {
      let isJPG = true;
      if (file.type !== "image/png" && file.type !== "image/jpeg") {
        this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
        isJPG = false;
      }
      let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
      if (!isLt) {
        this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
        this.uploadDisabled = false;
        isJPG = false;
      }
      return isJPG;
    },
    // 上传成功
    handleSuccessFunction(response, file, fileList) {
      this.addInfo.img = file.response.data.url;
    },
    // 文件超出个数限制时的钩子
    handleExceedScene() {
      this.$modal.notifyWarning(`产品图片只能上传一张图片`);
    },
    // 点击
    async editSubmit() {
      this.$refs.refAddInfo.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.editInfo.id) {
            let data = JSON.parse(JSON.stringify(this.addInfo));
            data.id = this.editInfo.id;
            res = await reqProductEdit({
              requestId: "",
              data,
            });
          } else {
            res = await reqProductAdd({
              requestId: "",
              data: this.addInfo,
            });
          }
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("操作成功");
          this.$parent.onProductList();
          this.closeEditDialog();
        }
      });
    },
    // 点击关闭弹框
    closeEditDialog() {
      this.uploadDisabled = false;
      this.$refs.refAddInfo.resetFields();
      this.fileList = [];
      this.dialogVisible = false;
    },
  },
  mounted() {
    this.addInfo.productKey = this.generateRandomString(16);
  },
  created() {
    this.baseUrl = `${this.$baseURL_copy}file/upload`;
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 隐藏加号
::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}

::v-deep .el_dialog .el-dialog__body {
  margin-bottom: 20px;
}

// ::v-deep .el-upload--picture-card {
//   background-color: rgba(0, 0, 0, 0s) !important;
// }
::v-deep .el-upload {
  background-color: rgba(0, 0, 0, 0s) !important;
}
</style>
